package com.shanxia.codec.cmd;

import com.shanxia.codec.Decoder;
import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

/**
 * S -> C
 * 服务器应答充电桩状态信息包
 * 后台服务器对收到充电桩状态报文后的应答
 */
@Data
public class Cmd103 extends ProtocolDataBase {

    public static final int MIN_SIZE = 6;

    private int v1;
    private int v2;
    private int chargingPortNum;                // 充电口号
    private boolean reportImmediately;          // 是否立即上报一次104报文  0-否；1-是

    public Cmd103(){
        super.setCmd(103);
    }

    public static Cmd103 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd103 cmd = new Cmd103();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = Decoder.getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = Decoder.getUint16(dataField, offset);
        offset += 2;
        // 1字节充电口号
        cmd.chargingPortNum = Decoder.getUint8(dataField[offset++]);
        // 1字节是否立即上报一次 104 报文
        cmd.reportImmediately = (Decoder.getUint8(dataField[offset]) == 1);
        return cmd;
    }

    @Override
    public byte[] getDataField() {
        int offset = 0;
        byte[] data = new byte[MIN_SIZE];
        Decoder.getBytesAsUint16(data, offset, this.v1);
        offset += 2;
        Decoder.getBytesAsUint16(data, offset, this.v2);
        offset += 2;
        // 1字节充电口号
        data[offset++] = (byte) chargingPortNum;
        // 1字节是否立即上报一次104报文
        data[offset++] = (byte) (reportImmediately ? 1 : 0);
        return data;
    }
}
